package com.ruoyi.stock.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.stock.domain.query.StockSectorQuery;
import com.ruoyi.stock.service.IStockInfoService;
import com.ruoyi.stock.service.impl.test.LonghuDataProcessor;
import com.ruoyi.stock.service.impl.test.LonghuResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.stock.mapper.StockSectorMapper;
import com.ruoyi.stock.domain.StockSector;
import com.ruoyi.stock.service.IStockSectorService;
import com.ruoyi.common.core.text.Convert;

/**
 * 股票板块Service业务层处理
 *
 * @author lzl
 * @date 2025-11-05
 */
@Service
public class StockSectorServiceImpl extends ServiceImpl<StockSectorMapper, StockSector> implements IStockSectorService {
    @Autowired
    private StockSectorMapper stockSectorMapper;

    @Autowired
    private IStockInfoService iStockInfoService;

    /**
     * 查询股票板块
     *
     * @param id 股票板块主键
     * @return 股票板块
     */
    @Override
    public StockSector selectStockSectorById(Long id) {
        return stockSectorMapper.selectStockSectorById(id);
    }

    /**
     * 查询股票板块列表
     *
     * @param stockSector 股票板块
     * @return 股票板块
     */
    @Override
    public List<StockSector> selectStockSectorList(StockSector stockSector) {
        return stockSectorMapper.selectStockSectorList(stockSector);
    }

    /**
     * 新增股票板块
     *
     * @param stockSector 股票板块
     * @return 结果
     */
    @Override
    public int insertStockSector(StockSector stockSector) {
        return stockSectorMapper.insert(stockSector);
    }

    /**
     * 修改股票板块
     *
     * @param stockSector 股票板块
     * @return 结果
     */
    @Override
    public int updateStockSector(StockSector stockSector) {
        return stockSectorMapper.updateById(stockSector);
    }

    /**
     * 批量删除股票板块
     *
     * @param ids 需要删除的股票板块主键
     * @return 结果
     */
    @Override
    public int deleteStockSectorByIds(String ids) {
        return stockSectorMapper.deleteStockSectorByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除股票板块信息
     *
     * @param id 股票板块主键
     * @return 结果
     */
    @Override
    public int deleteStockSectorById(Long id) {
        return stockSectorMapper.deleteById(id);
    }

    /**
     * 批量插入
     */
    public List<StockSector> batchInsert(String recordDate)  {
        //判断是否是历史日期
        Boolean isHistoryDate = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(!sdf.format(new Date()).equals(recordDate)) {
            isHistoryDate = true;
        }
        LonghuDataProcessor processor = new LonghuDataProcessor();
        System.out.println("开始获取龙虎榜数据...\n");
        // 1. 获取分类数据
        System.out.println("1. 获取分类数据");
        String url = "https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=RealRankingInfo&st=30&apiv=w21&Type=1&c=ZhiShuRanking&PhoneOSNew=1&ZSType=7&";
        if(isHistoryDate) {
            url = "https://apphis.longhuvip.com/w1/api/index.php?Order=1&a=RealRankingInfo&st=30&apiv=w21&Type=1&c=ZhiShuRanking&PhoneOSNew=1&ZSType=7&Date="+ recordDate;
        }
        LonghuResponse response = processor.fetchData(url);
        List<List<Object>> list = response.getList();
        List<StockSector> stockSectors = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (List<Object> ls : list) {
                if (CollectionUtils.isNotEmpty(ls)) {
                    try {
                        stockSectors.add(new StockSector((String) ls.get(0), (String) ls.get(1), (Double) ls.get(2), (Double) ls.get(3), sdf.parse(recordDate)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //System.out.println(JSON.toJSONString(stockSectors));
        // 2. 获取分类信息
        System.out.println("2. 获取分类数据");
        if (CollectionUtils.isNotEmpty(stockSectors)) {
            for (StockSector stockSector : stockSectors) {
                //判断是否有日期的数据
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("record_date", recordDate);
                queryWrapper.eq("code", stockSector.getCode());
                Long l = stockSectorMapper.selectCount(queryWrapper);
                if (l > 0) {
                    System.out.println("数据已经存在");
                } else {
                    this.save(stockSector);
                    System.out.println("2.1. 股票代码:" + stockSector.getCode());
                    iStockInfoService.handlerStockInfo(stockSector.getId(),stockSector.getCode(),isHistoryDate,recordDate);
                }
            }
        }
        return stockSectors;
    }

    /**
     * 获取板块列表
     *
     * @param stockSectorQuery
     * @return
     */
    @Override
    public List<StockSector> getStockSector(StockSectorQuery stockSectorQuery) {
        String recordDate = stockSectorQuery.getRecordDate();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("record_date", stockSectorQuery.getRecordDate());
        List<StockSector> list = this.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)) {
            return list;
        } else {
            return batchInsert(recordDate);
        }
    }
}
